// ~ Package Declaration
// ==================================================

package com.wms.utils.spring.editor;

import com.wms.data.WmsFrameworkException;
import com.wms.data.helper.DataHelper;
import com.wms.data.pojo.Pojo;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringUtils;


// ~ Comments
// ==================================================

/**
 * 
 * PropertyEditor - Pojo 屬性
 * 
 * <pre>
 * 歷史紀錄：
 * 2009/2/25 Timothy
 * 	新建檔案
 * </pre>
 * 
 * @author <pre>
 * SD
 * 	Timothy
 * PG
 * 
 * UT
 * 
 * MA
 * </pre>
 * @version $Rev$
 * 
 *          <p/>
 *          $Id$
 * 
 */
@SuppressWarnings("unchecked")
public class PojoEditor extends PropertyEditorSupport {

	// ~ Static Fields
	// ==================================================

	// ~ Fields
	// ==================================================

	private Class<? extends Pojo> pojoClass;
	private DataHelper dataHelper;

	// ~ Constructors
	// ==================================================

	public PojoEditor(DataHelper dataHelper, Class<? extends Pojo> pojoClass) {

		if (pojoClass == null) {

			throw new WmsFrameworkException("pojoClass could not null!", new NullPointerException());
		}

		this.pojoClass = pojoClass;
		this.dataHelper = dataHelper;
	}

	// ~ Methods
	// ==================================================

	/*
	 * 2009/2/25 Timothy
	 * 
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {

		if (StringUtils.isBlank(text)) {

			this.setValue(null);
		}
		else {

			try {

				this.setValue(this.dataHelper.findById(this.pojoClass, text));
			}
			catch (Exception e) {

				e.printStackTrace();

				// pojoClass  沒有找到相應實例！
				throw new WmsFrameworkException(this.pojoClass.getName() + " \u6c92\u6709\u627e\u5230\u76f8\u61c9\u5be6\u4f8b\uff01", e);
			}
		}
	}

}
